package com.bilubi.reggie.reggie.common;


import com.bilubi.reggie.reggie.enums.CodeEnum;
import com.bilubi.reggie.reggie.excpetion.CategoryDeleteException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<?> SqlExceptionHandle(Exception e){
        if (e.getClass().equals(DuplicateKeyException.class)) {
            return R.error(CodeEnum.ADD_ERROR);
        }
        else{
            log.error(e.getMessage());
            return R.error(CodeEnum.UNKNOWN_ERROR);
        }
    }

    @ResponseBody
    @ExceptionHandler(CategoryDeleteException.class)
    public R<?> CategoryDeleteExceptionHandle(Exception e){
        CategoryDeleteException ex = (CategoryDeleteException) e;
        CodeEnum codeEnum = ex.getCodeEnum();
        return R.error(codeEnum);
    }


}
